import React, { useRef, useEffect, useState } from 'react'
import { Card, Row, Col, Button, Space, Typography, Badge } from 'antd'
import { 
  ClearOutlined, 
  DownloadOutlined, 
  ReloadOutlined,
  BugOutlined,
  DatabaseOutlined
} from '@ant-design/icons'
import { useWebSocket } from '../../hooks/useWebSocket'
import { Utils } from '../../utils'
import './LogPanel.css'

const { Text } = Typography

const LogPanel = () => {
  const { backendLogs, serialLogs, connected } = useWebSocket()
  const backendLogRef = useRef(null)
  const serialLogRef = useRef(null)
  
  const [logStats, setLogStats] = useState({
    backendCount: 0,
    serialCount: 0,
    lastUpdate: null
  })

  // 自动滚动到底部
  const scrollToBottom = (ref) => {
    if (ref.current) {
      ref.current.scrollTop = ref.current.scrollHeight
    }
  }

  // 更新日志统计
  useEffect(() => {
    setLogStats({
      backendCount: backendLogs?.length || 0,
      serialCount: serialLogs?.length || 0,
      lastUpdate: new Date()
    })
  }, [backendLogs, serialLogs])

  // 自动滚动后端日志
  useEffect(() => {
    if (backendLogs && backendLogs.length > 0) {
      setTimeout(() => scrollToBottom(backendLogRef), 100)
    }
  }, [backendLogs])

  // 自动滚动串口日志
  useEffect(() => {
    if (serialLogs && serialLogs.length > 0) {
      setTimeout(() => scrollToBottom(serialLogRef), 100)
    }
  }, [serialLogs])

  // 清除日志
  const clearLogs = (type) => {
    // 这里可以发送清除日志的请求到后端
    Utils.showToast(`${type}日志已清除`, 'success')
  }

  // 导出日志
  const exportLogs = (type) => {
    const logs = type === 'backend' ? backendLogs : serialLogs
    if (!logs || logs.length === 0) {
      Utils.showToast('没有日志可导出', 'warning')
      return
    }

    const content = logs.join('\n')
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const filename = `${type}_logs_${timestamp}.txt`
    
    Utils.downloadFile(content, filename, 'text/plain')
    Utils.showToast(`${type}日志已导出`, 'success')
  }

  // 刷新日志
  const refreshLogs = () => {
    // 通过WebSocket请求最新日志
    Utils.showToast('正在刷新日志...', 'info')
  }

  // 格式化日志行
  const formatLogLine = (line, index) => {
    if (!line) return null

    // 检测日志级别
    let level = 'info'
    let className = 'log-line'
    
    if (line.toLowerCase().includes('error') || line.toLowerCase().includes('错误')) {
      level = 'error'
      className += ' log-error'
    } else if (line.toLowerCase().includes('warn') || line.toLowerCase().includes('警告')) {
      level = 'warning'
      className += ' log-warning'
    } else if (line.toLowerCase().includes('debug') || line.toLowerCase().includes('调试')) {
      level = 'debug'
      className += ' log-debug'
    } else if (line.toLowerCase().includes('success') || line.toLowerCase().includes('成功')) {
      level = 'success'
      className += ' log-success'
    }

    return (
      <div key={index} className={className}>
        <span className="log-index">{String(index + 1).padStart(3, '0')}</span>
        <span className="log-content">{line}</span>
      </div>
    )
  }

  const LogContainer = ({ title, logs, logRef, type, icon }) => (
    <Card 
      title={
        <Space>
          {icon}
          <span>{title}</span>
          <Badge 
            count={logs?.length || 0} 
            style={{ backgroundColor: connected ? '#52c41a' : '#f5222d' }}
          />
        </Space>
      }
      size="small"
      className="log-card"
      extra={
        <Space size="small">
          <Button 
            icon={<ReloadOutlined />}
            size="small"
            onClick={refreshLogs}
            disabled={!connected}
            title="刷新日志"
          />
          <Button 
            icon={<DownloadOutlined />}
            size="small"
            onClick={() => exportLogs(type)}
            disabled={!logs || logs.length === 0}
            title="导出日志"
          />
          <Button 
            icon={<ClearOutlined />}
            size="small"
            onClick={() => clearLogs(title)}
            disabled={!logs || logs.length === 0}
            title="清除日志"
          />
        </Space>
      }
    >
      <div className="log-container">
        <div 
          ref={logRef}
          className="log-content"
        >
          {logs && logs.length > 0 ? (
            logs.map((line, index) => formatLogLine(line, index))
          ) : (
            <div className="log-empty">
              <Text type="secondary">暂无日志数据</Text>
            </div>
          )}
        </div>
        <div className="log-footer">
          <Space split={<span style={{ color: '#666' }}>|</span>}>
            <Text style={{ fontSize: '11px', color: '#999' }}>
              共 {logs?.length || 0} 条
            </Text>
            {logStats.lastUpdate && (
              <Text style={{ fontSize: '11px', color: '#999' }}>
                更新: {logStats.lastUpdate.toLocaleTimeString()}
              </Text>
            )}
            <Text style={{ fontSize: '11px', color: connected ? '#52c41a' : '#f5222d' }}>
              {connected ? '已连接' : '未连接'}
            </Text>
          </Space>
        </div>
      </div>
    </Card>
  )

  return (
    <div className="log-panel">
      <Row gutter={[0, 16]}>
        {/* 单片机数据日志 */}
        <Col span={24}>
          <LogContainer
            title="单片机数据日志"
            logs={serialLogs}
            logRef={serialLogRef}
            type="serial"
            icon={<DatabaseOutlined style={{ color: '#1890ff' }} />}
          />
        </Col>

        {/* 后端日志 */}
        <Col span={24}>
          <LogContainer
            title="后端日志"
            logs={backendLogs}
            logRef={backendLogRef}
            type="backend"
            icon={<BugOutlined style={{ color: '#52c41a' }} />}
          />
        </Col>
      </Row>
    </div>
  )
}

export default LogPanel
